package 线程池;

import java.util.concurrent.*;

public class 原生api {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //使用原生线程池api来创建一个线程
        //线程池创建的时候，需要设置很多参数：
        //1. 核心线程数
        //2. 最大线程数
        //3. 空闲时间
        //4. 空闲时间单位
        //5. 阻塞队列
        //6. 线程创建的工厂对象
        //7. 队列满了，再存放时的拒绝策略
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                3,
                10,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                new ThreadPoolExecutor.AbortPolicy()
//                new ThreadPoolExecutor.CallerRunsPolicy()
//                new ThreadPoolExecutor.DiscardPolicy()
//                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        Future<Integer> f = pool.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 1;
            }
        });
        System.out.println(f.get());



        //原生的线程池，提交任务：使用execute/submit
        for(int i=0; i<10; i++){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }

        //还有4种便捷的创建方式
        //单线程池
        ExecutorService pool1 = Executors.newSingleThreadExecutor();
        //缓存的线程池
        ExecutorService pool2 = Executors.newCachedThreadPool();
        //固定大小的线程池
        ExecutorService pool3 = Executors.newFixedThreadPool(4);
        //计划任务的线程池
        ScheduledExecutorService pool4 = new ScheduledThreadPoolExecutor(4);
    }
}
